package com.zhanjixun.web.filter;

import com.google.common.collect.Lists;
import com.zhanjixun.api.domain.UserDTO;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author :zhanjixun
 * @date : 2019/9/3 20:32
 */
@Log4j
public class LoginFilter implements Filter {

    private List<String> exclusions = Lists.newArrayList();
    private String redirectUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String initParameter = filterConfig.getInitParameter("exclusions");
        redirectUrl = filterConfig.getInitParameter("redirectPage");
        String[] split = StringUtils.split(initParameter, ",");
        exclusions.addAll(Arrays.asList(split));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String servletPath = httpRequest.getServletPath();
        if (exclusions.contains(servletPath)) {
            filterChain.doFilter(httpRequest, httpResponse);
            return;
        }

        Object user = httpRequest.getSession().getAttribute("user");
        if (user instanceof UserDTO) {
            filterChain.doFilter(httpRequest, httpResponse);
            return;
        }
        httpResponse.sendRedirect(httpRequest.getContextPath() + redirectUrl);
    }

    @Override
    public void destroy() {

    }
}
